<?php

use Carbon\Carbon;

/**
 * 货币·判断并获取货币编码或符号
 * @param $currency string|int 货币
 * @param $encode bool 默认true，返回货币的编码，否则返回货币的符号
 *
 * @param string|int|false 如无匹配值则返回false
 * */
function currency ($currency, $encode=true)
{

	return $encode
		? (currency_encode(is_numeric($currency) ? currency_decode($currency) : $currency)) // 编码
		: (currency_decode(is_numeric($currency) ? $currency : currency_encode($currency)));// 符号

}



/**
 * 货币·转化为编码
 * @param $currency string 货币符号
 *
 * @param int|false 如无匹配值则返回false
 * */
function currency_encode ($currency)
{
	if ($currency===false) return false;
	return \App\Model\SQL::translationBack('currency', $currency);
}


/**
 * 货币·解析为符号
 * @param $currency int 货币编码
 *
 * @param string|false 如无匹配值返回false
 * */
function currency_decode ($currency)
{
	if ($currency===false) return false;
	$currency = @\App\Model\SQL::translation('currency')[$currency];
	return $currency ? $currency : false;
}


/**
 * 获取指定当天所在月份的汇率
 * @param string|int $currency
 * @param string|int $to
 * @param date $date 默认今天
 * @return float|null
 */
function exchange ($currency, $to, $date=null)
{
    return \App\Services\CurrencyExchange::exchange($currency, $to, $date);
}

/**
 * 报关价格 = 采购价格*2*汇率（USD）
 */
function decPrice($price, $currency)
{
    $ex = $currency !=1 ? exchange($currency,'USD'): 1;
    return $ex * $price * 2;
}

/**
 * 清关价格= 采购价*汇率*0.8  （USD）
 */
function clearPrice($price, $currency)
{
    $ex = $currency != 1 ? exchange($currency,'USD'): 1;
    return $ex * $price * 0.8;
}



/**
 * 获取财务账期
 * @param int $month 默认0表示当下账期，负数或者正数表示增加或减去当前月份后的账期
 */
function finTerm ($month=0)
{
    return Carbon::now()->addMonths($month)->format('Ym');
}


function finTermOffset ($term, $month)
{
    return Carbon::create(finTermYear($term), finTermMonth($term), 1)->addMonths($month)->format('Ym');
}

function finTermYear ($term)
{
    return substr($term, 0, 4);
}


function finTermMonth ($term)
{
    return substr($term, 5);
}


/**
 * 财务账期始末时间
 * @param int $term 账期
 * @param bool $start 第一天或最后一天
 * @param string $format 返回的时间格式
 */
function finTermTime ($term, $start=true, $format='Y-m-d')
{
    $term = Carbon::create(finTermYear($term), finTermMonth($term), 1);
    return $start ? $term->format($format) : $term->lastOfMonth()->format($format);
}


